//webrtc分机注册
let userAgent;
let remoteAudio;
let incomingSession;
let incomingCallAudio;
let oSipStack;
let oSipSessionCall;
let constraints = {audio: true,video: {faceMode: 'user'}};
let hangupTone;
let currentSession;
export let socket;

import './jssip.js';
import * as CtiClient from './ctiClient.js';
/**
 * 
 * @param {*} exten 座席分机
 * @param {*} agentno 座席工号
 * @param {*} password 分机密码
 * @param {*} WEBRTC_SERVICE webrtc服务器连接地址
 * @param {*} MQTT_SERVICE mq服务器连接地址
 */
export function register(exten,agentno,password,WEBRTC_SERVICE,MQTT_SERVICE){
      socket=null;
      console.log("do sipRegistering "+agentno+ ":address " + WEBRTC_SERVICE, MQTT_SERVICE);
      if(!remoteAudio){
            remoteAudio=new Audio();
      }
      if(!incomingCallAudio){
            incomingCallAudio = new Audio('./static/sounds/incoming-call-ringtone.wav')
      }
      if(!hangupTone){
            hangupTone = new Audio('./static/sounds/hanguptone.wav')
      }
	  remoteAudio.autoplay = true;
      // 进行号码登录注册
      var me_uri_joint = 'sip:'+exten+'@'+WEBRTC_SERVICE;
      var ws_uri = 'ws://'+WEBRTC_SERVICE+':7070';
      var contact_uri = me_uri_joint + ';transport=ws';

      if(MQTT_SERVICE.indexOf('wss')>-1){  //MQTT_SERVICE包含wss，表示是https形式
          ws_uri = 'wss://'+WEBRTC_SERVICE+':7071';
          contact_uri  = me_uri_joint + ';transport=wss';
      }
      //   创建websocket
      socket = new JsSIP.WebSocketInterface(ws_uri);
      //  配置参数
      var configuration = {
          sockets: [socket],
          //outbound_proxy_set: ws_uri,
          uri: me_uri_joint,
          password: password,
          register: true,  //指示JsSIP用户代理是否应在启动时自动注册
          contact_uri: contact_uri,
          ws_servers: ws_uri
          //session_timers: false  //启用会话定时器,默认值是true。
      };
      //  配置创建user agent
     userAgent = new JsSIP.UA(configuration);
      //成功注册成功
     userAgent.on('registered', function (data) {
          console.info("registered: ", data.response.status_code, ",", data.response.reason_phrase);
          setTimeout(function () {
            CtiClient.sendMessage("signin",'');
          },2000);
      });
      //由于注册失败而被解雇
     userAgent.on('registrationFailed', function (data) {
          console.log("registrationFailed, ", data);
      });
      // 在注册期间发射几秒钟，如果应用程序没有为这个事件设置任何监听器，JsSIP将像往常一样重新注册。
     userAgent.on('registrationExpiring', function () {
          //过期之后将自动重新注册
          console.warn("registrationExpiring");
          //重新注册
          userAgent.register()
      });
      // 注销下线事件
      userAgent.on('unregistered', function () {
          console.warn("unregistered");
      });

      //为传入或传出的会话/呼叫。
     userAgent.on('newRTCSession', function (data) {
          console.info('onNewRTCSession: ', data);
          if (data.originator == 'remote') {//来电呼入
        	  incomingSession = data.session;
                incomingCallAudio.play();
                incomingCallAudio.loop = true;
                localStorage.setItem('showIncoming', '1')
              //data.session.answer({ 'mediaConstraints':constraints, 'mediaStream': null });
          } else {//去电呼出
              console.info("outgoingSession");
              outgoingSession = data.session;
              outgoingSession.on('connecting', function(data) {
                //通话状态
                Callstate.innerText = "连接中";
                globalCallPhoneStates = "连接中";
                console.info('onConnecting - ', data.request);
                currentSession = outgoingSession;
                outgoingSession = null;
              });
          }

		  //远程挂断事件
		  data.session.on("ended", function(data) {
                  console.log("call end", data);
                  currentSession = null;
                  startHangupTone();
                  // clearVideo();
		  });
		
          data.session.on('accepted', function (data) {
              console.info('onAccepted - ', data);
              if (data.originator == 'remote' && currentSession == null) {
                  currentSession = incomingSession;
                  incomingSession = null;
                  console.info("setCurrentSession - ", currentSession);
              }
            //   接听后不再振铃
              if(incomingCallAudio){
                incomingCallAudio.pause();
              }
          });

          data.session.on('confirmed', function (data) {
              console.info('onConfirmed - ', data);
              if (data.originator == 'remote' &&currentSession == null) {
            	  currentSession = incomingSession;
                  incomingSession = null;
                  console.info("setCurrentSession - ",currentSession);
              }
          });

          data.session.on('sdp', function (data) {
              console.info('onSDP, type - ', data.type, ' sdp - ', data.sdp);
          });

          data.session.on('progress', function (data) {
              console.info('onProgress - ', data.originator);
              if (data.originator == 'remote') {
                  console.info('onProgress, response - ', data.response);
              }
          });

          data.session.on('peerconnection', function (data) {
              console.info('onPeerconnection - ', data.peerconnection);
              data.peerconnection.onaddstream = function(ev) {
                  console.info('onaddstream from remote - ', ev);
				  remoteAudio.srcObject = ev.stream;
                //   if(that.haveVideo == '1' && that.callType != '0' && that.isScreen){
                    doAgentVideo(ev.stream);
                    // console.info("isOK");
                //   }
              };
          });

          data.session.on('addstream', function(e){
              console.info('on addstream - ');
              incomingCallAudio.pause();
              remoteAudio.src = e.stream;
          });

          data.session.on('failed', function(e){
              console.info('on failed - ');
		      // recEvent("failed","");
              if(incomingSession!=null){
            	  incomingSession = null;
              }
              currentSession = null;
              incomingCallAudio.pause();
          });

          if(data.session.direction === 'incoming'){
          }

      });
      /**
        * 连接到信令服务器，如果是之前停止则恢复到停止之前的状态，如果是刷新操作‘’
        * 而且configuration的register参数设置为true则直接注册到信令服务器
        */
     userAgent.start();
}

/**
 * 分机注销
 */
export function unRegested() {
    var options = {
      all: true
    };
    if(userAgent!=null){
      console.log("do unregister");
      userAgent.unregister(options);
      userAgent = null
    }
    
}

/**
 * 应答
 */
export function sipAnswer(){
      // if(useVideo){
      //       initVideo();
      // }
      sipCall("call-audio");
      incomingCallAudio.pause();
      incomingSession.answer({ 'mediaConstraints': constraints, 'mediaStream': null });
}

/**
 * 应答
 */
export function hangUp(){
      let options = {
            all: false
        };
        if (incomingSession != null) {
            currentSession = null;
            incomingCallAudio.pause();
            incomingSession.terminate(options);
        } else {
            userAgent.terminateSessions(options); //终止当前对话
        }
}

//呼叫
function sipCall(s_type, txtPhoneNumber){
      var max_bandwidth = "";
      var video_size = "";
            if (oSipStack && !oSipSessionCall && !tsk_string_is_null_or_empty(txtPhoneNumber)){
                  if (s_type == 'call-screenshare') {
                        if (!SIPml.isScreenShareSupported()) {
                              tsk_utils_log_info("Screen sharing not supported. Are you using chrome 26+?");
                              return;
                        }
                        if (!location.protocol.match('https')) {
                              if (confirm("Screen sharing requires https://. Do you want to be redirected?")){
                                    sipUnRegister();
                                    //window.location = 'https://ns313841.ovh.net/call.htm';
                                    tsk_utils_log_info("必须支持https请求");
                              }
                              return;
                        }
                  }
                  
                  // create call session
                  oSipSessionCall = oSipStack.newSession(s_type, oConfigCall);
                  // make call
                  if (oSipSessionCall.call(txtPhoneNumber) != 0) {
                        oSipSessionCall = null;
                        tsk_utils_log_info("Failed to make call");
                        return;
                  }
            } else if (oSipSessionCall) {
                  tsk_utils_log_info("'<i>Connecting...</i>");
                  oSipSessionCall.accept(oConfigCall);
            }
}

function startHangupTone() {
      try { 
      //     if(ctiConfig.phoneType != 0){
          hangupTone.loop = false;
          hangupTone.play(); 
      // }
      } catch (e) { }
}

export function sendDtmf(value){
    if(currentSession){
        currentSession.sendDTMF(value);
    }
}